package com.aiti.lulian.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.service.ILuLianEnterpriseService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.vo.EnterpriseAdminUserVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/***
 * 企业和用户的关系
 */
@RestController
@RequestMapping("/eu")
public class LuLianEnterpriseUserController extends WebController<LuLianEnterpriseUser> {

    private final ILuLianEnterpriseUserService luLianEnterpriseUserService;

    private final ILuLianEnterpriseService luLianEnterpriseService;

    public LuLianEnterpriseUserController(ILuLianEnterpriseUserService luLianEnterpriseUserService, ILuLianEnterpriseService luLianEnterpriseService) {
        this.luLianEnterpriseUserService = luLianEnterpriseUserService;
        this.luLianEnterpriseService = luLianEnterpriseService;
    }

    /***
     * 通过用户Id查询企业Id
     * @param userId
     * @return
     */
    @GetMapping("/queryEnterpriseIdByUserId/{userId}")
    public Message queryEnterpriseIdByUserId(@PathVariable("userId") String userId){
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(enterpriseUser == null){
            return Message.fail();
        }
        return Message.success(enterpriseUser.getEnterpriseId());
    }



    /**
     * 生成员工加入企业的二维码
     * @return
     */
    @GetMapping("/generateEnterpriseQRCode")
    public Message generateEnterpriseQRCode(){
        //获取当前登陆人的Id
        String userId = findUserId();
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", userId));
        if(enterpriseUser == null){
            throw new RuntimeException("没有找到当前用户所邦定的企业");
        }
        LuLianEnterprise enterprise = luLianEnterpriseService.getOne(new QueryWrapper<LuLianEnterprise>().eq("base_id", enterpriseUser.getEnterpriseId()));
        if(enterprise == null){
            throw new RuntimeException("没有找到当前用户所邦定的企业信息");
        }
        String url = "https://yunzhanting.org.cn?weceid=%s";

        byte[] bytes = QrCodeUtil.generatePng(StringUtils.format(url, enterprise.getBaseId()), 300, 300);
        byte[] imageBase64 = Base64.encodeBase64(bytes);
        String base64Image = new String(imageBase64);
        Map<String,String> map = new HashMap<String,String>(16) {
            {put("base64Image", base64Image);}
            {put("success", "true");}
        };
        return Message.success(map);
    }

    @PostMapping("/bindEnterpriseUser")
    public Message bindEnterpriseUser(@RequestBody Map<String,String> enterpriseUserInfo){
        List<LuLianEnterpriseUser> list = luLianEnterpriseUserService.list(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", enterpriseUserInfo.get("userId")));
        if(list != null && list.size() > 0){
            return Message.fail("该用户已邦定其他企业");
        }
        LuLianEnterpriseUser enterpriseUser = LuLianEnterpriseUser.builder()
                .baseId(IdUtil.simpleUUID())
                .enterpriseId(enterpriseUserInfo.get("enterpriseId"))
                .userId(enterpriseUserInfo.get("userId"))
                .build();
        luLianEnterpriseUserService.save(enterpriseUser);
        return Message.success();
    }

    /**
     * 根据用户ID判断当前用户在 show_enterprise_user表 中是否存在关联记录
     * ***** 定制接口，慎用，非常规逻辑 *****
     */
    @GetMapping("/isBound")
    public Message isBound(@RequestParam("userId") String userId) {
        List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserService.list(new LambdaQueryWrapper<LuLianEnterpriseUser>().eq(LuLianEnterpriseUser::getUserId, userId));
        if (enterpriseUserList.size() == 0) {
            // 尚未存在与企业的关联记录，返回false
            return Message.success(false);
        } else if (enterpriseUserList.size() > 1) {
            //若存在多条，先删掉多余记录，任意留下一条记录，再返回true
            luLianEnterpriseUserService.removeByIds(enterpriseUserList.stream().map(LuLianEnterpriseUser::getBaseId).collect(Collectors.toList()).subList(1, enterpriseUserList.size()));
            return Message.success(true);
        } else {
            //当有且只存在一条时，直接返回true
            return Message.success(true);
        }
    }

    @PostMapping("/batchBindEnterpriseUser")
    public Message batchBindEnterpriseUser(@RequestBody List<Map<String,String>> params){

        if(params == null || params.isEmpty()){
            return Message.fail();
        }

        List<LuLianEnterpriseUser> list = new ArrayList<LuLianEnterpriseUser>();

        for(Map<String,String> temp : params){

            String userId = temp.get("userId");
            String enterpriseId = temp.get("enterpriseId");

            LuLianEnterpriseUser enterpriseUser = LuLianEnterpriseUser.builder()
                    .baseId(IdUtil.simpleUUID())
                    .enterpriseId(enterpriseId)
                    .userId(userId)
                    .build();
            list.add(enterpriseUser);
            if(list.size() >= 200){
                luLianEnterpriseUserService.saveBatch(list);
                list.clear();
            }
        }
        if(!list.isEmpty()){
            luLianEnterpriseUserService.saveBatch(list);
            list.clear();
        }
        return Message.success();
    }

    @DeleteMapping("/deleteBind")
    public Message deleteBind(@RequestParam("userId") String userId) {
        luLianEnterpriseUserService.remove(new LambdaQueryWrapper<LuLianEnterpriseUser>().eq(LuLianEnterpriseUser::getUserId, userId));
        return Message.success();
    }

    @ApiOperation("获取所选企业的企业管理员账号信息")
    @GetMapping("/enterpriseAdminUser")
    public Message enterpriseAdminUser(@RequestParam("enterpriseId") String enterpriseId) {
        List<EnterpriseAdminUserVo> enterpriseAdminUser = luLianEnterpriseService.getEnterpriseAdminUser(enterpriseId);
        if(CollectionUtils.isNotEmpty(enterpriseAdminUser)){
            if(enterpriseAdminUser.size() == 1){
                return Success(enterpriseAdminUser.get(0));
            }else{
                return Fail("检测到当前绑定了多个主账号，请修改主账号的绑定情况，再进行添加操作。");
            }
        }else{
            return Message.fail("检测到您添加的企业未开通数智名片，开通请联系：13047487654");
        }

    }

//    @ApiOperation("根据用户ID获取该用户关联的企业的相关数据")
//    @GetMapping("/getEnterpriseInfoByUserId")
//    public Message getEnterpriseInfoByUserId(@RequestParam("userId") String userId){
//        return luLianEnterpriseUserService.getEnterpriseInfoByUserId(userId);
//    }
}